<template>
  <!-- 运行结果-查看动因数据 -->
  <div class="driver-data">
    <el-row class="ruleResult container">
      <el-col style="margin-right:10px;" class="content-left">
        <!-- 操作区域 -->
        <upper-template exportIcon :searchIcon="false" @exportData="exportDriverData"
        >
          <!-- 显示隐藏区 -->
          <template slot="columnHide">
            <el-checkbox-group v-model="checkDriverList">
              <el-checkbox
                v-for="item in textDriverData"
                :label="item.label"
                :key="item.prop"
                >{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </upper-template>
        <div style="height:400px">
          <el-table ref="multipleDriverTable" :data="tableDriverData" style="width: 100%" @row-click="authorizeForDriverTable">
            <el-table-column
              width="55"
              type="selection"
              
            ></el-table-column>
            <el-table-column
              prop="ruleCode"
              label="规则编码"
               show-overflow-tooltip
              v-if="columnDriverState[0]"
            >
            </el-table-column>
            <el-table-column
              prop="ruleName"
              label="规则名称 "
               show-overflow-tooltip
              v-if="columnDriverState[1]"
            >
            </el-table-column>

            <el-table-column
              prop="driverCode"
              label="动因编码 "
               show-overflow-tooltip
              v-if="columnDriverState[2]"
            >
            </el-table-column>

            <el-table-column
              prop="driverName"
              label="动因名称 "
               show-overflow-tooltip
              v-if="columnDriverState[3]"
            >
            </el-table-column>
          </el-table>
          <pagination
            @size-change="handleDriverSizeChange"
            @current-change="handleDriverCurrentChange"
            :current-page="searchDriverForm.page"
            :page-size="searchDriverForm.size"
            @refresh="searchDriverFunc"
            :total="driverTotal"
          ></pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ruleResult } from "@/api/index";
import { caRuleDriverApi } from "@/api/index";
import upperTemplate from "@/components/upperTemplate.vue"
import onlyOneSearch from "@/components/onlyOneSearch";
import moment from "moment";
export default {
  data() {
    return {
      // 列隐藏依据数据
      textDriverData: [
        { prop: "ruleCode", label: "规则编码", disabled: true },
        { prop: "ruleName", label: "规则名称", disabled: true },
        { prop: "driverCode", label: "动因编码", disabled: true },
        { prop: "driverName", label: "动因名称", disabled: true }
      ],
      // 显示的列
      checkDriverList: [],
      //查询时默认条件
      searchDriverForm: {
        page: 1,
        size: 15
      },
      //总条数
      driverTotal: 0,
      tableDriverData: []
    };
  },
  props: {
    ruleCode: {
      type: String,
      default: ""
    },
    ruleType: {
      type: String,
      default: ""
    },
    beginTime: {
      type: String,
      default: ""
    },
    activeName: {
      type: String,
      default: ""
    }
  },
  watch: {
    ruleCode: function(newVal, oldVal) {
      this.ruleCode = newVal;
      newVal&&this.searchDriverFunc();
    },
    ruleType: function(newVal, oldVal) {
      this.ruleType = newVal;
    },
    beginTime: function(newVal, oldVal) {
      this.beginTime = newVal;
    },
    activeName: function(newVal, oldVal) {
      this.activeName = newVal;
      if (this.activeName == 'driverDataModel') {
        this.searchDriverFunc();
      }
    }
  },
  components: {
    onlyOneSearch
  },
  created() {
    //初始化显示的列
    this.checkDriverListInit();
  },
  computed: {
    columnDriverState() {
      let arr = [],
        arr1 = this.textDriverData,
        arr2 = this.checkDriverList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
    ruleCodeStatus: function() {
      return this.ruleCode;
    },
    ruleTypeStatus: function() {
      return this.ruleType;
    },
    beginTimeStatus: function() {
      return this.beginTime;
    }
  },
  mounted() {
    this.searchDriverFunc()
  },
  methods: {
    checkDriverListInit() {
      this.checkDriverList = this.textDriverData.map(v => {
        return v.label;
      });
    },
    searchDriverFunc() {
      let data= {
        ruleCode:this.ruleCode,
        ruleType:this.ruleType,
        beginTime: moment(this.beginTime).format("YYYY-MM-DD HH:mm:ss"),
        ...this.searchDriverForm
      }
      ruleResult.queryRunResultPage(data).then(res => {
        if (res.code === 200) {
          this.tableDriverData = res.datas.rows;
          this.driverTotal = res.datas.total;
        }
      });
    },
    ruleNameFormatter() {
      return this.ruleName;
    },
    //点击行选中(运行结果首页)
    authorizeForDriverTable(row) {
      if (this.$refs.multipleDriverTable) {
          this.$refs.multipleDriverTable.clearSelection()
      }
      this.$refs.multipleDriverTable.toggleRowSelection(row, true)
    },
    exportDriverData () {
      let checked = this.$refs.multipleDriverTable.selection;
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        let driverType = checked[0].driverType;
        let driverCode = checked[0].driverCode;
        if(driverType == "S") {
          this.expDataForStatic(driverCode);
        } else {
          this.expDataForDynamic(driverCode);
        }
      }
    },
    //静态导出
    expDataForStatic(val) {
      let data = {
        driverCode:val
      };
      ruleResult.getSqlForStaticExport(data).then(res => {
        if (res.code === 200) {
          let sql = res.message;
          if(sql != undefined&&sql.length > 0) {
            let exportData = {
              sqlOnly:sql,
              tableName:"STATIC_DRIVER_DATA",
              driverCode:val
            };
            ruleResult.getExportFile(exportData).then((response) => {
              if(response.code==500&&response.message=="2") {
                this.$message.error('执行SQL查询数据错误');
              } else if (response) {
                var filename = decodeURI(response.headers['content-disposition']).split('=')[1];
                var blob = new Blob([response.data],{
                  type:
                  "application/vnd.ms-excel;charset=utf-8"
                });
                if (window.navigator.msSaveOrOpenBlob) {
                  navigator.msSaveBlob(blob,filename);
                } else {
                  var downloadElement = document.createElement("a");
                  var href = window.URL.createObjectURL(blob); //创建下载的链接
                  downloadElement.href = href;
                  downloadElement.download = filename; //下载后文件名
                  document.body.appendChild(downloadElement);
                  downloadElement.click(); //点击下载
                  document.body.removeChild(downloadElement); //下载完成移除元素
                  window.URL.revokeObjectURL(href); //释放掉blob对象
                }
              } else {
                this.$message.error(res.message || '获取失败');
              }
            })
          }
        }
      });
    },
    //动态导出
    expDataForDynamic(val) {
      caRuleDriverApi.ruleDriverfindTableEn({driverCode:val}).then(res =>{
        if(res.code == 200&&res.data != undefined&&res.data.length>0){
          let id = res.data;
          caRuleDriverApi.ruleDriverfindbyDriverCode({driverCode:val}).then(res=>{
            if(res.code == 200&&res.datas != undefined) {
              if(res.datas.ASOFDATE==null) {
                this.$message.error(res.message || '获取失败');
              } else {
                let queryData = res.datas;
                let exportData = {
                  tableName:id,
                  PHYTABLENAME:id,
                  columnType:"1",
                  sqlId:"driver",
                  DRIVERCODE:val,
                  FILTERID:queryData.FILTERID,
                  DATAFILTERID:queryData.DATAFILTERID,
                  PHYSICALCOLUMN:queryData.PHYSICALCOLUMN,
                  ASOFDATE:queryData.ASOFDATE
                };
                ruleResult.getExportFile(exportData).then((response) => {
                  if(response.code==500&&response.message=="2") {
                    this.$message.error('执行SQL查询数据错误');
                  } else if (response) {
                    var filename = decodeURI(response.headers['content-disposition']).split('=')[1];
                    var blob = new Blob([response.data],{
                      type:
                      "application/vnd.ms-excel;charset=utf-8"
                    });
                    if (window.navigator.msSaveOrOpenBlob) {
                      navigator.msSaveBlob(blob,filename);
                    } else {
                      var downloadElement = document.createElement("a");
                      var href = window.URL.createObjectURL(blob); //创建下载的链接
                      downloadElement.href = href;
                      downloadElement.download = filename; //下载后文件名
                      document.body.appendChild(downloadElement);
                      downloadElement.click(); //点击下载
                      document.body.removeChild(downloadElement); //下载完成移除元素
                      window.URL.revokeObjectURL(href); //释放掉blob对象
                    }
                  } else {
                    this.$message.error(res.message || '获取失败');
                  }
                })
              }
            }
          })
        }
      });
    },
    handleDriverSizeChange(val) {
      this.searchDriverForm.size = val;
      console.log(val, "每页数");
      this.searchDriverFunc();
    },
    handleDriverCurrentChange(val) {
      this.searchDriverForm.page = val;
      console.log(val, "当前页");
      this.searchDriverFunc();
    },
    exportData() {
      console.log("调用导出")
    }
  }
};
</script>

<style lang="scss" scoped>
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
</style>